package com.andrew.servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.jasper.tagplugins.jstl.core.ForEach;

import com.andrew.entity.Customer;
import com.andrew.service.CustomerService;
import com.andrew.service.impl.CustomerServiceImpl;

public class registerServlet  extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req,resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("UTF-8");
		String emailKey="";
		CustomerService cs=new CustomerServiceImpl();
		String username=req.getParameter("username");
		String realName=req.getParameter("realName");
		int gender=Integer.parseInt(req.getParameter("gender"));
		String IDcard=req.getParameter("IDcard");
		String phone=req.getParameter("phone");
		
		String emailCheck=req.getParameter("emailCheck");
		
		
		Cookie[] cookies=req.getCookies();
		for(Cookie cookie:cookies) {
			String cookiename=cookie.getName();
			if("emailKey".equals(cookiename)) {
				emailKey=cookie.getValue();
			}
			
		}

		//判断邮箱验证
		if(!emailKey.equals(emailCheck)) {
			resp.getWriter().write("emailCheck False");
			return ;
		}
		//判断是否身份证和电话是否有问题
		if(IDcard.length()!=18||phone.length()!=11) {
			//身份证又问题
			resp.getWriter().write("iDNunber or Phone wrong");
			return;
		}
		String password=req.getParameter("password");
		Customer customer=new Customer();
		customer.setUserName(username);
		customer.setRealName(realName);
		customer.setGender(gender);
		customer.setIDNumber(IDcard);
		customer.setTelephone(phone);
		customer.setPASSWORD(password);
		
		try {
			String result = cs.register(customer);
			if(result.equals("success")) {
				//成功
				//req.getSession().setAttribute("register", "success");
				resp.getWriter().write("success");
				
			}else {
				//失败
				//req.getSession().setAttribute("register", "fail");
				resp.getWriter().write("fail");
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}
}
